package app.android.com.wuandroidapp.sample;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.google.zxing.activity.CaptureActivity;
import com.utils.CommonUtil;

import java.util.ArrayList;
import java.util.List;

import app.android.com.utilscode.util.ToastUtils;
import app.android.com.wuandroidapp.AndroidApplication;
import app.android.com.wuandroidapp.R;
import app.android.com.wuandroidapp.library.activity.BaseNoTitleActivity;
import app.android.com.wuandroidapp.test.model.db.entities.minimalist.FaceMapModel;
import butterknife.BindView;
import butterknife.ButterKnife;

public class Main2Activity extends BaseNoTitleActivity {

    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.baidu_map)
    MapView baiduMap;


    BaiduMap mBaiduMap;
    @BindView(R.id.sao)
    Button sao;
    @BindView(R.id.iv_loction)
    ImageView ivLoction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        ButterKnife.bind(this);
        titleText.setText("单车");
        ivTitleRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        mBaiduMap = baiduMap.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        getbaimap();
        ivLoction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LocationClient mLocClient = new LocationClient(Main2Activity.this);  //定位用到的一个类
                ///LocationClientOption类用来设置定位SDK的定位方式，
                LocationClientOption option = new LocationClientOption(); //以下是给定位设置参数
                option.setOpenGps(true); // 打开gps
                option.setCoorType("bd09ll"); // 设置坐标类型
                option.setScanSpan(0);
                mLocClient.setLocOption(option);
                mLocClient.start();
                mLocClient.registerLocationListener(new BDLocationListener() {
                    @Override
                    public void onReceiveLocation(BDLocation location) {
                        getlocs(location);
                    }

                    @Override
                    public void onConnectHotSpotMessage(String s, int i) {

                    }
                });
            }
        });
        sao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //打开二维码扫描界面
                if (CommonUtil.isCameraCanUse()) {
                    Intent intent = new Intent(Main2Activity.this, CaptureActivity.class);
                    startActivityForResult(intent, 100);
                } else {
                    Toast.makeText(Main2Activity.this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        /**
         * 地图状态发生变化
         */
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener()

        {
            public void onMapStatusChangeStart(MapStatus status) {
                //     updateMapState();
            }

            public void onMapStatusChangeFinish(MapStatus status) {
                //          updateMapState();
            }

            public void onMapStatusChange(MapStatus status) {
                //      updateMapState();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (resultCode == 0xA1) { //RESULT_OK = -1
                Bundle bundle = data.getExtras();
                String scanResult = bundle.getString("qr_scan_result");
                //将扫描出的信息显示出来
                ToastUtils.showLong(scanResult);
            }
        }
    }

    LatLng p;
    String city;
    String la;
    String lo;
    BDLocation location;

    public void getbaimap() {
        if (p != null) {
        } else {
            if (AndroidApplication.getInstance().locations != null) {

                getlocs(AndroidApplication.getInstance().locations);
            } else {
                AndroidApplication.getInstance().mLocationClient.registerLocationListener(new BDLocationListener() {
                    @Override
                    public void onReceiveLocation(BDLocation location) {
                        getlocs(location);
                    }

                    @Override
                    public void onConnectHotSpotMessage(String s, int i) {

                    }
                });
            }
        }

    }

    public void getlocs(BDLocation location) {
        MyLocationData locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(100).latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);

        location = AndroidApplication.getInstance().locations;
        p = new LatLng(location.getLatitude(), location.getLongitude());
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(p)
                .zoom(20)
                .build();
        city = location.getCity();
        la = location.getLatitude() + "";
        lo = location.getLongitude() + "";
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mBaiduMap.setMapStatus(mMapStatusUpdate);
        mBaiduMap.animateMapStatus(mMapStatusUpdate);
        if(mapModels.size()<=0){
            getmapService("1", location.getCity(), location.getLatitude() + "", location.getLongitude() + "");
        }
    }

    List<FaceMapModel> mapModels = new ArrayList<>();

    boolean ismap = true;

    public void getmapService(String d, String city, String place_la, String place_lo) {
        if (ismap) {
            ismap = false;

            for (int i = 0; i < 5; i++) {
                FaceMapModel faceMapModel = new FaceMapModel();
                faceMapModel.setPlace_la((Double.parseDouble(la) + i * 0.001) + "");
                faceMapModel.setPlace_lo((Double.parseDouble(lo) + i * 0.001) + "");
                faceMapModel.setName("女皇护卫");
                faceMapModel.setContent("为皇女殿下效力");
                mapModels.add(faceMapModel);
            }
            for (int i = 0; i < 5; i++) {
                FaceMapModel faceMapModel = new FaceMapModel();
                faceMapModel.setPlace_la((Double.parseDouble(la) - i * 0.001) + "");
                faceMapModel.setPlace_lo((Double.parseDouble(lo)) + "");
                faceMapModel.setName("女皇护卫");
                faceMapModel.setContent("为皇女殿下效力");
                mapModels.add(faceMapModel);
            }
            handler.sendEmptyMessageAtTime(200, 50);
        }
    }

    ArrayList<MarkerOptions> marks = new ArrayList<>();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
                    ismap = true;
                    //     LocationUtil.getInstance().stop();
                    //通过系统提供的实例获得一个LayoutInflater对象
                    mBaiduMap.clear();
                    LayoutInflater inflater = (LayoutInflater) Main2Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    final MapStatus ms = mBaiduMap.getMapStatus();
                    View views = inflater.inflate(R.layout.view_photo, null);
                    //       ImageView imgeview = (ImageView) views.findViewById(R.id.view_photo);
//                    BitmapDescriptor bdGround = BitmapDescriptorFactory
//                            .fromView(views);
                    BitmapDescriptor bdGround = BitmapDescriptorFactory.fromResource(R.mipmap.ic_ovlay_photo);

                    if (mapModels.size() > 0) {
                        for (int i = 0; i < mapModels.size(); i++) {
                            //第一个参数为xml文件中view的id，第二个参数为此view的父组件，可以为null，android会自动寻找它是否拥有父组件

                            final FaceMapModel mapModel = mapModels.get(i);
                            final String modelsi = i + "";

                            //在这里面调用百度地图api

                            double la = Double.parseDouble(mapModel.getPlace_la());
                            double lo = Double.parseDouble(mapModel.getPlace_lo());

                            LatLng p1 = new LatLng(la, lo);
                            MarkerOptions op = new MarkerOptions()
                                    .position(p1)
                                    .title(modelsi)
                                    .icon(bdGround);

                            marks.add(op);
                            for (int j = 0; j < marks.size(); j++) {

                                mBaiduMap.addOverlay(marks.get(j));
                            }
                            MapStatus mMapStatus = new MapStatus.Builder()
                                    .target(p)
                                    .zoom(ms.zoom)
                                    .build();
                            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                            //改变地图状态
                            mBaiduMap.setMapStatus(mMapStatusUpdate);
                            mBaiduMap.animateMapStatus(mMapStatusUpdate);

                        }
                    }
                    break;
                case 400:
                    ismap = true;
                    //      LocationUtil.getInstance().stop();
                    break;
            }
        }
    };


    public void back(View v) {
        //   finish();
   startActivity(new Intent(Main2Activity.this,PersonActivity.class));
    }

}
